package com.weiyirong99.crm.app.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;


import org.greenrobot.eventbus.EventBus;


import java.text.SimpleDateFormat;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;


/**
 * @Description:
 * @Author: zdx
 * @CreateDate: 2020/9/10
 * @UpdateDate: 2020/9/10
 * @Version: 1.0
 */
public abstract class BaseActivity extends AppCompatActivity {
    public String TAG = this.getClass().getName();
//    public QMUITipDialog tipDialog;
//    public MMKV kv = MMKV.defaultMMKV();

    public Gson mGson = new Gson();
    public  static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        Bundle bundle = getIntent().getExtras();
        setContentView(getLayout());
        initView();
        initParms(bundle);
//        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this);
//        }
    }

    public abstract int getLayout();

    public abstract void initView();

    @Override
    protected void onResume() {
        super.onResume();

    }

    /**
     * [绑定控件]
     *
     * @param resId
     * @return T  控件类型
     */
    @SuppressWarnings("unchecked")
    protected <T extends View> T $(int resId) {
        return super.findViewById(resId);
    }

    /**
     * 添加本地配置存储
     *
     * @param key
     * @param val
     */
    public void set(String key, String val) {
        SharedPreferences.Editor config = getSharedPreferences("config", Context.MODE_PRIVATE).edit();
        config.putString(key, val);
        config.apply();
    }


    /**
     * 权限申请码
     */
    private final static int RESULT_CODE_REQUEST = 52032;
    private final static int RESULT_CODE_SETTINGS = 32520;

    private void goToSettings() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivityForResult(intent, RESULT_CODE_SETTINGS);
    }

    private static Toast toast = null;

    /**
     * 无重复无延时显示toast
     */
    @SuppressLint("CheckResult")
    public void ts(String content) {
        Observable.just(content)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        if (toast != null) {
                            toast.cancel();
                        }
                        toast = Toast.makeText(getActivity(), s, Toast.LENGTH_LONG);
                        WindowManager windowManager = (WindowManager) getActivity().getSystemService(WINDOW_SERVICE);
                        Point size = new Point();
                        windowManager.getDefaultDisplay().getSize(size);
                        toast.setGravity(Gravity.BOTTOM, 0, size.y / 3);
                        toast.setText(s);
                        toast.show();

                    }
                });
    }

    /**
     * 获取存储内容
     *
     * @param key
     * @return
     */
    public String get(String key) {
        SharedPreferences config = getSharedPreferences("config", Context.MODE_PRIVATE);
        return config.getString(key, null);
    }

    /**
     * [初始化参数]
     *
     * @param parms
     */
    public abstract void initParms(Bundle parms);

    /**
     * 获取Sp
     *
     * @param key name
     * @return
     */
    public SharedPreferences getSp(String key) {
        return getActivity().getSharedPreferences(key, Context.MODE_PRIVATE);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    hideSoftInput();
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public abstract BaseActivity getActivity();

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            // 点击的是输入框区域，保留点击EditText的事件
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        return false;
    }

    protected void hideSoftInput() {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

//    public int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

//    @Subscribe
//    public void onEventMainThread(MessageWrap wrap) {
//        switch (wrap.tag) {
//            case MessageWrap.USB_DISABLE: {
//                ts((String) wrap.data);
//                break;
//            }
//            case MessageWrap.FILE_NOTSDCARD:
//            case MessageWrap.USB_DISPARTITION: {
//                new QMUIDialog.MessageDialogBuilder(getActivity())
//                        .setTitle("提示")
//                        .setMessage((String) wrap.data)
//                        .setSkinManager(QMUISkinManager.defaultInstance(this))
//                        .addAction(0, "好的", QMUIDialogAction.ACTION_PROP_POSITIVE, new QMUIDialogAction.ActionListener() {
//                            @Override
//                            public void onClick(QMUIDialog dialog, int index) {
//                                dialog.dismiss();
//                            }
//                        })
//                        .create(mCurrentDialogStyle).show();
//                break;
//            }
//
//        }
//    }

}
